In [1]:
import io
import spotipy

import numpy as np

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

import os

import pandas as pd

from collections import Counter, OrderedDict
from spotipy.oauth2 import SpotifyOAuth
import requests

import plotly.graph_objects as go
import plotly.express as px

from IPython.display import Image
In [2]:
scope = 'user-top-read'
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope,open_browser=False))
In [3]:
my_playlists = sp.current_user_playlists(limit=50, offset=0)

terms = ['short_term', 'medium_term', 'long_term']

all_genres = []
all_names = []

for i in range(3):
    top50 = sp.current_user_top_artists(limit=20,offset=0,time_range=terms[i])

    for j, item in enumerate(top50['items']):
        all_genres += item['genres']
        all_names += [item['name']]
In [4]:
def CountFrequency(my_list):
 
    freq = {}
    for item in my_list:
        if (item in freq):
            freq[item] += 1
        else:
            freq[item] = 1
        
    return freq

It seems like I mostly listen to pop, rap, r&b, and k-pop.¶

I'm surprised that rap comes 2nd in this list as I thought I listen to more r&b on a regular basis. I suspect that what I think is r&b is labelled as rap by Spotify.¶

In [5]:
genre_freq = CountFrequency(all_genres)

gdf = pd.DataFrame(genre_freq,index=['number']).T.sort_values(by='number',ascending=False)

gdf.head(7)

fig = px.pie(gdf, values='number', names=gdf.index)
fig.show()

Data shows that I don't really favor a particular subset of artists.¶

In [6]:
names_freq = CountFrequency(all_names)

ndf = pd.DataFrame(names_freq,index=['number']).T.sort_values(by='number',ascending=False)

ndf.head(7)

fig1 = px.pie(ndf, values='number', names=ndf.index)
fig1.show()
In [7]:
sml = []
pop = [],[],[]
artist = [],[],[]
pop_score = 0

for i in range(3):

    results = sp.current_user_top_artists(time_range=terms[i], limit=10)

    for j, item in enumerate(results['items']):
        popularity = item['popularity']
        pop_score += popularity
        artist[i].append(item['name'])
        pop[i].append(popularity)
    sml.append(popularity)

plt.rcParams["figure.figsize"] = (20,3)

for i in range(3):
    print(terms[i])
    print(artist[i])
    print("-"*10)
    df = pd.DataFrame({"x" : pop[i]})

    cmap = mcolors.LinearSegmentedColormap.from_list("", ["grey", "pink", "purple"])
    
    plt.bar(artist[i], df["x"], color=cmap(df.x.values/100))
    plt.xlabel('Artists', labelpad=12)
    plt.xticks(rotation=90)
    
    plt.title("Top 10 Artists ("  + terms[i] + ")")
    plt.show()
short_term
['Drake', 'PARTYNEXTDOOR', 'The Weeknd', 'Future', 'Jay Park', 'Pop Smoke', 'SZA', 'Chris Brown', 'Kehlani', 'Khalid']
----------
medium_term
['Drake', 'The Weeknd', 'PARTYNEXTDOOR', 'Future', 'Bryson Tiller', 'Khalid', 'LE SSERAFIM', 'Chase Atlantic', 'Chris Brown', 'Giveon']
----------
long_term
['Red Velvet', 'The Weeknd', 'Drake', 'Future', 'Bryson Tiller', 'Ariana Grande', 'PARTYNEXTDOOR', 'IU', 'Khalid', 'Leessang']
----------
In [8]:
artists = [],[],[]
tracks = [],[],[]
track_pop = [],[],[]

for i in range(3):
    results = sp.current_user_top_tracks(limit=10,offset=0,time_range=terms[i])
    
    text = ""
        
    for j, item in enumerate(results['items']):
        popularity = item['popularity']
        track = item['name']
        track_pop[i].append(popularity)
        tracks[i].append(track)
        
        target = item['artists']
        name = target[0]
        artist = name['name']
        artists[i].append(artist)
        
    df2 = pd.DataFrame({"x" : track_pop[i]})

    cmap = mcolors.LinearSegmentedColormap.from_list("", ["lightsteelblue", "cornflowerblue", "blue"])
    
    plt.bar(tracks[i], df2["x"], color=cmap(df2.x.values/100))
    plt.xlabel('Tracks', fontsize=10)
    plt.xticks(rotation=90)
    plt.title(" Top Tracks (" + terms[i] + ")")
    plt.show()
/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 45320 (\N{HANGUL SYLLABLE NEO}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 51032 (\N{HANGUL SYLLABLE YI}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 47784 (\N{HANGUL SYLLABLE MO}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 46304 (\N{HANGUL SYLLABLE DEUN}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 49692 (\N{HANGUL SYLLABLE SUN}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 44036 (\N{HANGUL SYLLABLE GAN}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 54756 (\N{HANGUL SYLLABLE HE}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 50612 (\N{HANGUL SYLLABLE EO}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 51648 (\N{HANGUL SYLLABLE JI}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 47803 (\N{HANGUL SYLLABLE MOS}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 54616 (\N{HANGUL SYLLABLE HA}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 45716 (\N{HANGUL SYLLABLE NEUN}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 50668 (\N{HANGUL SYLLABLE YEO}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 51088 (\N{HANGUL SYLLABLE JA}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 46496 (\N{HANGUL SYLLABLE DDEO}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 45208 (\N{HANGUL SYLLABLE NA}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 44032 (\N{HANGUL SYLLABLE GA}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 45224 (\N{HANGUL SYLLABLE NAM}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 51221 (\N{HANGUL SYLLABLE JEONG}) missing from current font.

/home/devillish_red/spotify-data-analysis/myenv/lib/python3.10/site-packages/IPython/core/pylabtools.py:152: UserWarning:

Glyph 51064 (\N{HANGUL SYLLABLE IN}) missing from current font.

In [9]:
colors = ['pink','tan','cornflowerblue']

for i, artist in enumerate(artists):
    df3 = pd.DataFrame(artist)
    c = Counter(df3[0])
    y = OrderedDict(c.most_common())
    df4 = pd.DataFrame({"x" : c})
    plt.bar(c.keys(), y.values(),color=colors[i])
    plt.xticks(rotation=90)

    plt.xlabel('Artists', fontsize=10)
    plt.title("Songs per Artist in Top 50 (" + terms[i] + ")")
    plt.show()
    if i == 2:
        buf = io.BytesIO()
        plt.savefig(buf, format = 'png')
        buf.seek(0)
    
<Figure size 2000x300 with 0 Axes>
In [ ]: